const TOOLBAR =[
	{content:"添加", icon:"el-icon-document-add",type:"primary"},
	{content:"删除", icon:"el-icon-delete",type:"danger"},
]

let validate = {
    validatePass: (rule, value, callback) => {
  //       if (value !== app.form.password) {
  //           callback(new Error('两次输入密码不一致!'));
  //       } else if (value.length < 6) {
		// 	callback(new Error('密码不能小于六位!'));
		// } else {
  //           callback();
  //       }
    }
};

const rules = {
    companyname: [
        {required: true, message: '请输入公司名称', trigger: 'blur'}
    ],
    businessscope: [
        {required: true, message: '请输入经营范围', trigger: 'blur'}
    ],
    registeredcapital: [
        {required: true, message: '请输入注册资金', trigger: 'blur'}
    ],
    registeredaddress: [
        {required: true, message: '请选择注册地址', trigger: 'blur'}
    ],
    ishouseinvoice: [
        {required: true, message: '请选择房屋发票', trigger: 'blur'}
    ],
    liaisons: [
        {required: true, message: '请输入联系人', trigger: 'blur'}
    ],
    phonenumber: [
        {required: true, message: '请输入联系电话', trigger: 'blur'},
		 {pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的联系电话', trigger: 'blur'}
    ],
    hander: [
        {required: true, message: '请选择负责人', trigger: 'blur'}
    ]
};
			
let app = new Vue({
    el: "#app",
    data() {
        return {
        	leftbar_show:true,
			imgdialogImageUrl: '',
			imgdialogVisible: false,
			pickerOptions: {
			  shortcuts: [{
				text: '最近一周',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
				  picker.$emit('pick', [start, end]);
				}
			  }, {
				text: '最近一个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
				  picker.$emit('pick', [start, end]);
				}
			  }, {
				text: '最近三个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
				  picker.$emit('pick', [start, end]);
				}
			  }]
			},
			uploadurl:axios.defaults.baseURL + "api/image/upload/gongshang/",
			headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
			// 添加、编辑标识
			action:"",
			tableHeight:window.innerHeight - 180,
			toolbar:TOOLBAR,
			// tablecolums:COLUMNS,
			dialogFormVisible:false,
			queryForm:{
                companyname: "",
                liaisons: "",
                createtime: "",
                status: [],
			},
			rules, // 数据验证规则
            form: {
				id: null,
                companyname: [""],
                businessscope: "",
                registeredcapital: "",
                registeredaddress: "",
                securities: [],
                leasingagreements: [],
                ishouseinvoice: "",
				chaptermoment:[],
				liaisons:"",
				phonenumber:"",
				createtime:"",
				urgent:"",
				status:"",
				hander:"",
				detail:[]
            },
			users:[], // 用户列表
			multipleSelection:[],
			tableData: [], // 所有查询结果集
			pagedata:[],  // 当前页结果集
			loaded:false,
			pageNo:1, // 当前页码
			pagesize:25 ,// 每页记录数
			securitiesfileList: [], // 产权证上传临时列表
			leasingagreementsfileList: [] ,// 租赁协议上传临时列表
			idcardsList:{}// 身份证上传临时列表
        }
    },
	methods: {
		// 显示侧边栏
		showLeftBar() {
			if (this.leftbar_show) {
				this.leftbar_show = false
			} else {
				this.leftbar_show = true
			}
		},
		addTokenToTempfilelist(filelist) {
			var tempfilelist = []
			for (let s of filelist) {
				if (typeof(s.response) != "undefined") {
					tempfilelist.push({
						name: s.response.data.name,
						url: s.response.data.url+ "/" + localStorage.getItem('TOKEN')
					});
				} else {
					tempfilelist.push({
						name: s.name,
						url: s.url
					});
				}
			}
			return tempfilelist;
		},
		clearCompanyname(){
			for (var i = this.form.companyname.length-1;i>=0;i--) {
				if (this.form.companyname[i]=="") {
					this.form.companyname.splice(i,1);
				}
			}
		},
		addCompanyname(index){
			if (index == this.form.companyname.length-1) {
				this.form.companyname.push("")
			}
		},
		handleAvatarSuccessSecurities(res,file,filelist){
			this.securitiesfileList = this.addTokenToTempfilelist(filelist);
		},
		handleRemoveSecurities(file, filelist) {
			this.securitiesfileList = this.addTokenToTempfilelist(filelist);
	    },
		handleAvatarSuccessLeasingagreements(res,file,filelist){
			this.leasingagreementsfileList = this.addTokenToTempfilelist(filelist);
		},
		handleRemoveLeasingagreements(file, filelist) {
			this.leasingagreementsfileList = this.addTokenToTempfilelist(filelist);
	    },
		handleAvatarSuccessidcards(res,file,filelist, title){
			this.idcardsList[title] = this.addTokenToTempfilelist(filelist);
		},
		handleRemoveidcards(file, filelist, title) {
			this.idcardsList[title] = this.addTokenToTempfilelist(filelist);
	    },
		 
		handlePictureCardPreview(file) {
			this.imgdialogImageUrl = file.url;
			this.imgdialogVisible = true;
	    },
		beforeAvatarUpload(file) {
            const isJPG = ["image/jpeg","image/jpg","image/png"].indexOf(file.type) > -1;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('图片只能是png,jpeg,jpg格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                return false;
            }
            return true;
        },	
		addTokenTo(filelist) {
			// URL后加TOKEN
			for (let j in filelist) {
				filelist[j].url = filelist[j].url + "/" + localStorage.getItem('TOKEN')
			}
		},
		// 表格多选 
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// 确认
		async cofirm(){
            this.$refs.form.validate(async valid => {
                if (valid){
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						// 清除多余的空公司名称
						this.clearCompanyname();
						
						// 去除产权证件TOKEN
						this.form.securities = []
						for (let i in this.securitiesfileList) {
							index = this.securitiesfileList[i].url.lastIndexOf('/');
							this.securitiesfileList[i].url = this.securitiesfileList[i].url.substring(0,index)
						}
						this.form.securities = this.securitiesfileList;
						
						// 去除租凭协议TOKEN
						this.form.leasingagreements = []
						for (let i in this.leasingagreementsfileList) {
							index = this.leasingagreementsfileList[i].url.lastIndexOf('/');
							this.leasingagreementsfileList[i].url = this.leasingagreementsfileList[i].url.substring(0,index)
						}
						this.form.leasingagreements = this.leasingagreementsfileList;
						
						// 去除身份证照片TOKEN
						for (let i in this.form.detail) {
							for (let j in this.idcardsList[this.form.detail[i].title]) {
								index = this.idcardsList[this.form.detail[i].title][j].url.lastIndexOf('/');
								this.idcardsList[this.form.detail[i].title][j].url = this.idcardsList[this.form.detail[i].title][j].url.substring(0,index)
							}
						}
						for (let i in this.form.detail) {
							this.form.detail[i].idcards = this.idcardsList[this.form.detail[i].title];
						}
						let res = null;
						if (this.action=="add") {
							res = await axios.put('api/gongshangzhuce/add', this.form);
						} else{
							res = await axios.put('api/gongshangzhuce/update', this.form);
						}
						if (res.code === 200) {
							this.query();
							this.dialogFormVisible = false
						}else {
							this.$message.error(res.message);
						}					

					}catch (e) {
						this.$message.error('请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
                }
            })			
		},

		// 查询
		async query() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/gongshangzhuce/query', this.queryForm);
				if (res.code === 200) {
					// 照片URL后加TOKEN
					for (let i in res.data) {
						for (let j in res.data[i].securities) {
							res.data[i].securities[j].url = res.data[i].securities[j].url + "/" + localStorage.getItem('TOKEN')
						}
						for (let j in res.data[i].leasingagreements) {
							res.data[i].leasingagreements[j].url = res.data[i].leasingagreements[j].url + "/" + localStorage.getItem('TOKEN')
						}
						for (let j in res.data[i].detail) {
							for (let k in res.data[i].detail[j].idcards) {
								res.data[i].detail[j].idcards[k].url = res.data[i].detail[j].idcards[k].url + "/" + localStorage.getItem('TOKEN')
							}
						}
					}
					this.tableData = res.data;
					this.loadPageData();
					this.$message.success(res.message);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			// 关闭加载框
			loading.close();
		},
		delmenber(index) {
			this.form.detail.splice(index,1);
		},
		addmember() {
			var gdNo = this.form.detail.length - 2;
			if (this.form.detail.length >= 3) {
				this.form.detail.push(
					{
					title:"股东" + gdNo,
					name:"",
					idnumber:"",
					phonenumber:"",
					capitalratio:"",
					idcards:[]
					}
				)
			} else {
				var menbers = [];
				for (let men of this.form.detail) {
					menbers.push(men.title);
				}
				var title = "";
				if (!menbers.includes("法人")) {
					title = "法人"
				} else if (!menbers.includes("监事")) {
					title = "监事"
				} else {
					title = "财务"
				}
				this.form.detail.push(
						{
						title:title,
						name:"",
						idnumber:"",
						phonenumber:"",
						capitalratio:"",
						idcards:[]
						}
					)
			}
		},
		async getAllUsers() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/user/all');
				if (res.code === 200) {
					this.users = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		toolAction(acName) {
			if (acName == "添加") {
				this.add()
			} else if (acName == "删除") {
				this.delete()
			}
		},
		async delete() {
			try {
				ids =[]
				for (let row of this.multipleSelection) {
					ids.push(row.id)
				}
				if (ids.length > 0) {
					this.$confirm('此操作将永久删除选定的行, 是否继续?', '提示', {
									confirmButtonText: '确定',
									cancelButtonText: '取消',
									type: 'warning'
								}).then(async () => {
									let res = await axios.put('api/gongshangzhuce/delete', ids);
									if (res.code === 200) {
										this.query();
										this.dialogFormVisible = false
									}else {
										this.$message.error(res.message);
									}					
								}).catch((e) => {
									if (e.message) this.Msg('error', e.message);
								});
				} else {
					this.$message.error('请先选择要删除的数据行！');
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
		},
		selectionChange(selection){
			this.selection = selection
		},
		// 添加
		add() {
			this.action="add";
			this.dialogFormVisible = true;
            this.form= {
				id: null,
                companyname: [""],
                businessscope: "",
                registeredcapital: "",
                registeredaddress: "公司提供",
                securities: [],
                leasingagreements: [],
                ishouseinvoice: "有",
				chaptermoment:["公章","发票章","法人章","财务章"],
				liaisons:"",
				phonenumber:"",
				createtime:"",
				urgent:"否",
				status:"客户填写中",
				hander:"",
				paytype:"认缴",
				taxtype:"小规模",
				comtype:"有限公司",
				detail:[
					{
					title:"法人",
					name:"",
					idnumber:"",
					phonenumber:"",
					capitalratio:"",
					idcards:[]
					},
					{title:"监事",
					name:"",
						idnumber:"",
						phonenumber:"",
						capitalratio:"",
						idcards:[]
					},
					{title:"财务",
					name:"",
						idnumber:"",
						phonenumber:"",
						capitalratio:"",
						idcards:[]
					},
					{title:"股东1",
					name:"",
						idnumber:"",
						phonenumber:"",
						capitalratio:"",
						idcards:[]
					},
					{title:"股东2",
					name:"",
						idnumber:"",
						phonenumber:"",
						capitalratio:"",
						idcards:[]
					},
					{title:"法股东3",
					name:"",
						idnumber:"",
						phonenumber:"",
						capitalratio:"",
						idcards:[]
					}
					
				]
				
            }
			this.initFilelist();
		},
		// 编辑
		edit(index, row) {
			this.action="edit"
			this.index = index;
			this.dialogFormVisible = true;
			this.form = deepCopy(row)
			console.log(this.form.securities)
			this.initFilelist();
		},
		// 初始化图像临时列表
		initFilelist() {
			this.securitiesfileList= this.form.securities;
			this.leasingagreementsfileList= this.form.leasingagreements;
			for (let i in this.form.detail) {
				this.idcardsList[this.form.detail[i].title] = this.form.detail[i].idcards;
			}
			
		},
		// 设定表格当前页
		handleCurrentPageChange (selectedPageNo) {
		  this.pageNo = selectedPageNo
		  // 加载数据页
		  this.loadPageData()
		},
		// 加载数据页
		loadPageData(){
			this.pagedata = [];
			var sno = 0;
			var eno = 0;
			// 分页
			if (this.pageNo*this.pagesize > this.tableData.length) {
				sno = this.tableData.length-this.tableData.length%this.pagesize;
				eno = this.tableData.length;
			} else {
				sno = this.pageNo*this.pagesize - this.pagesize;
				eno = this.pageNo*this.pagesize;
			}
			for (var i = sno; i < eno;i++) {
				this.pagedata.push(this.tableData[i])
			}
		},
	},
	async mounted() {
		// 自动调整表格高度
		window.onresize = () => {
		  return (() => {
			this.tableHeight = window.innerHeight - 180
		  })()
		}
		// 初始化用户列表
		this.getAllUsers();
		// // 初始化工商注册列表
		// this.query();
	}

});	